<template>
    <!-- 引用外部svg资源 -->
    <div
      v-bind="$attrs"
      v-if="isEternal"
      :style="styleEternalIcon"
      class="svg-eternal-icon svg-icon"
      :class="className"
    ></div>

    <!-- 引用内部svg资源 -->
    <svg
      v-else
      v-bind="$attrs"
      :class="className"
      class="svg-icon"
      aria-hidden="true"
    >
      <use :xlink:href="iconName" />
    </svg>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import { isEternal as eternal } from '@/utils/validate'
// 定义props
const props = defineProps({
  // icon图标
  icon: {
    type: String,
    require: true
  },
  // 图标class类
  className: {
    type: String,
    default: ''
  }
})

// 判断当前资源是否是外部资源
const isEternal = computed(() => eternal(props.icon))

// 外部图标样式
const styleEternalIcon = computed(() => (
  {
    mask: `url(${props.icon}) no-repeat`,
    '-webkit-mask': `url(${props.icon}) no-repeat`
  }
))

// 项目内图标
const iconName = computed(() => `#icon-${props.icon}`)

</script>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.svg-eternal-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
